/******************************************************/
/* Goblin's Cube - Rubik's cube game for Wii Homebrew */
/* Copyright (C) 2009 Ricardo Bueno Cordeiro          */
/* Licensed under de GNU General Public License v2.0  */
/*   See license_gplv2.txt for detalis                */
/******************************************************/

#include "sound_wave_loader.h"

#define U32_LITTLE_TO_BIG(u) ((((u) & 0x000000ff) << 24) | (((u) & 0x0000ff00) << 8) | (((u) & 0x00ff0000) >> 8) | (((u) & 0xff000000) >> 24))
#define U16_LITTLE_TO_BIG(u) ((((u) & 0xff00) >> 8) | (((u) & 0x00ff) << 8))

SoundWaveLoader::SoundWaveLoader(const u8 *file, u32 size) {
	// Store sound description
	this->fmt = (struct wave_fmt_block_t *)(file + sizeof(struct riff_file_t) + sizeof(struct wave_header_t));

	// Get data address
	this->data = (struct wave_data_block_t *)(((u8 *)fmt) + sizeof(struct wave_block_header_t) + U32_LITTLE_TO_BIG(fmt->header.size));
}

u32 SoundWaveLoader::get_size() {
	return U32_LITTLE_TO_BIG(data->header.size);
}

s32 SoundWaveLoader::get_pitch() {
	return (s32)U32_LITTLE_TO_BIG(fmt->sample_rate);
}

u16 SoundWaveLoader::get_num_bits_per_sample() {
	return U16_LITTLE_TO_BIG(fmt->significant_bits);
}

u16 SoundWaveLoader::get_num_channel() {
	return U16_LITTLE_TO_BIG(fmt->num_channel);
}

void SoundWaveLoader::get_samples(void *buffer, u32 start, u32 size) {
	u16 bits = this->get_num_bits_per_sample();

	register u8 *src = ((u8 *)(&(data->samples))) + start;
	register u8 *dst = (u8 *)buffer;
	register u8 *end = src + size;

	if (bits == 8) {
		while(src < end)
			*dst++ = *src++;
	} else if (bits == 16) {
		while(src < end) {
			*dst++ = *(src + 1);
			*dst++ = *src;
			src += 2;
		}
	}
}
